package cn.baddonkey.superqueryjavasdk.json;

import cn.baddonkey.superqueryjavasdk.exception.JsonProcessingException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.Setter;

import java.lang.reflect.Type;

public class JacksonParser implements JsonParser {
    @Getter
    @Setter
    private ObjectMapper objectMapper;

    public JacksonParser() {
        this.objectMapper = new ObjectMapper();
        // 在反序列化时忽略在 json 中存在但 Java 对象不存在的属性
        this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 在序列化时忽略值为 null 的属性
        this.objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 空字符串可以反序列化为 null
        objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
        // 支持 LocalDateTime
        this.objectMapper.findAndRegisterModules();
    }

    @Override
    public <T> T from(String json, Class<T> type) {
        try {
            return this.objectMapper.readValue(json, type);
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            throw new JsonProcessingException(e);
        }
    }

    @Override
    public <T> T from(String json, Type type) {
        try {
            return this.objectMapper.readValue(json, (JavaType) this.getType(type));
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            throw new JsonProcessingException(e);
        }
    }

    @Override
    public String to(Object o) {
        try {
            return this.objectMapper.writeValueAsString(o);
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            throw new JsonProcessingException(e);
        }
    }

    @Override
    public Type getType(Type type) {
        return this.objectMapper.getTypeFactory().constructType(type);
    }
}
